package com.education.ai.service.impl;

import com.education.ai.dao.TeachingPlanDao;
import com.education.ai.entity.TeachingPlan;
import com.education.ai.service.TeachingPlanService;
import com.education.ai.util.TeacherContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class TeachingPlanServiceImpl implements TeachingPlanService {

    @Autowired
    private TeachingPlanDao teachingPlanDao;

    @Override
    public List<TeachingPlan> findAll() {
        return teachingPlanDao.findAll();
    }
    
    @Override
    public List<TeachingPlan> findAll(Pageable pageable) {
        int offset = (int) pageable.getOffset();
        int limit = pageable.getPageSize();
        
        // 获取所有数据，然后手动进行分页
        List<TeachingPlan> allPlans = teachingPlanDao.findAll();
        
        // 应用排序（如果有）
        if (pageable.getSort().isSorted()) {
            // 由于没有直接支持排序的方法，这里暂时不处理排序
            log.warn("排序功能在JDBC实现中尚未支持，忽略排序条件");
        }
        
        // 手动分页
        int fromIndex = Math.min(offset, allPlans.size());
        int toIndex = Math.min(fromIndex + limit, allPlans.size());
        
        return allPlans.subList(fromIndex, toIndex);
    }

    @Override
    public TeachingPlan findById(Long id) {
        return teachingPlanDao.findById(id)
                .orElseThrow(() -> new RuntimeException("未找到教学计划，ID: " + id));
    }

    @Override
    @Transactional
    public TeachingPlan save(TeachingPlan teachingPlan) {
        // 设置关联的教师ID
        String currentTeacherId = TeacherContext.getCurrentTeacherId();
        if (currentTeacherId != null && (teachingPlan.getTeacherId() == null || teachingPlan.getTeacherId().isEmpty())) {
            log.info("为教学计划关联教师ID: {}", currentTeacherId);
            teachingPlan.setTeacherId(currentTeacherId);
        }
        
        return teachingPlanDao.save(teachingPlan);
    }

    @Override
    @Transactional
    public void deleteById(Long id) {
        teachingPlanDao.deleteById(id);
    }

    @Override
    public List<TeachingPlan> findBySubject(String subject) {
        return teachingPlanDao.findBySubject(subject);
    }

    @Override
    public List<TeachingPlan> findByGrade(String grade) {
        return teachingPlanDao.findByGrade(grade);
    }

    @Override
    public List<TeachingPlan> findTemplates() {
        // 由于dao层没有直接提供findByIsTemplateTrue方法
        // 这里先获取所有教学计划，然后筛选出isTemplate为true的记录
        return teachingPlanDao.findAll().stream()
                .filter(plan -> Boolean.TRUE.equals(plan.getIsTemplate()))
                .collect(Collectors.toList());
    }
    
    @Override
    public List<TeachingPlan> findByTeacherId(String teacherId) {
        return teachingPlanDao.findByTeacherId(teacherId);
    }
    
    @Override
    public List<TeachingPlan> findByTeacherId(String teacherId, Pageable pageable) {
        int offset = (int) pageable.getOffset();
        int limit = pageable.getPageSize();
        
        List<TeachingPlan> teacherPlans = teachingPlanDao.findByTeacherId(teacherId);
        
        // 手动分页
        int fromIndex = Math.min(offset, teacherPlans.size());
        int toIndex = Math.min(fromIndex + limit, teacherPlans.size());
        
        return teacherPlans.subList(fromIndex, toIndex);
    }
    
    @Override
    public long count() {
        return teachingPlanDao.count();
    }
    
    @Override
    public long countByTeacherId(String teacherId) {
        return teachingPlanDao.findByTeacherId(teacherId).size();
    }

    @Override
    public List<TeachingPlan> searchAll(String search, Pageable pageable) {
        int offset = (int) pageable.getOffset();
        int limit = pageable.getPageSize();
        
        // 获取所有数据，然后进行搜索过滤
        List<TeachingPlan> allPlans = teachingPlanDao.findAll();
        List<TeachingPlan> filteredPlans = allPlans.stream()
            .filter(plan -> matchesSearch(plan, search))
            .collect(Collectors.toList());
        
        // 手动分页
        int fromIndex = Math.min(offset, filteredPlans.size());
        int toIndex = Math.min(fromIndex + limit, filteredPlans.size());
        
        return filteredPlans.subList(fromIndex, toIndex);
    }

    @Override
    public List<TeachingPlan> searchByTeacherId(String teacherId, String search, Pageable pageable) {
        int offset = (int) pageable.getOffset();
        int limit = pageable.getPageSize();
        
        // 获取教师的所有计划，然后进行搜索过滤
        List<TeachingPlan> teacherPlans = teachingPlanDao.findByTeacherId(teacherId);
        List<TeachingPlan> filteredPlans = teacherPlans.stream()
            .filter(plan -> matchesSearch(plan, search))
            .collect(Collectors.toList());
        
        // 手动分页
        int fromIndex = Math.min(offset, filteredPlans.size());
        int toIndex = Math.min(fromIndex + limit, filteredPlans.size());
        
        return filteredPlans.subList(fromIndex, toIndex);
    }

    @Override
    public long countBySearch(String search) {
        return teachingPlanDao.findAll().stream()
            .filter(plan -> matchesSearch(plan, search))
            .count();
    }

    @Override
    public long countByTeacherIdAndSearch(String teacherId, String search) {
        return teachingPlanDao.findByTeacherId(teacherId).stream()
            .filter(plan -> matchesSearch(plan, search))
            .count();
    }

    /**
     * 检查教学计划是否匹配搜索关键词
     */
    private boolean matchesSearch(TeachingPlan plan, String search) {
        if (search == null || search.trim().isEmpty()) {
            return true;
        }
        
        String searchLower = search.toLowerCase();
        return (plan.getTitle() != null && plan.getTitle().toLowerCase().contains(searchLower)) ||
               (plan.getSubject() != null && plan.getSubject().toLowerCase().contains(searchLower)) ||
               (plan.getGrade() != null && plan.getGrade().toLowerCase().contains(searchLower)) ||
               (plan.getContent() != null && plan.getContent().toLowerCase().contains(searchLower)) ||
               (plan.getObjectives() != null && plan.getObjectives().toLowerCase().contains(searchLower)) ||
               (plan.getActivities() != null && plan.getActivities().toLowerCase().contains(searchLower)) ||
               (plan.getResources() != null && plan.getResources().toLowerCase().contains(searchLower)) ||
               (plan.getAssessment() != null && plan.getAssessment().toLowerCase().contains(searchLower));
    }

    @Override
    public List<TeachingPlan> findByTeacherIdWithFilters(String teacherId, String stage, String grade, String subject, Pageable pageable) {
        log.info("根据教师ID[{}]和筛选条件查询教学计划 - 阶段: {}, 年级: {}, 学科: {}", 
                teacherId, stage, grade, subject);
        
        List<TeachingPlan> plans = teachingPlanDao.findByTeacherId(teacherId);
        return filterAndPaginatePlans(plans, stage, grade, subject, pageable);
    }

    @Override
    public List<TeachingPlan> findAllWithFilters(String stage, String grade, String subject, Pageable pageable) {
        log.info("查询所有教学计划 - 筛选条件: 阶段: {}, 年级: {}, 学科: {}", 
                stage, grade, subject);
        
        List<TeachingPlan> plans = teachingPlanDao.findAll();
        return filterAndPaginatePlans(plans, stage, grade, subject, pageable);
    }

    @Override
    public long countByTeacherIdWithFilters(String teacherId, String stage, String grade, String subject) {
        log.info("统计教师[{}]的教学计划数量 - 筛选条件: 阶段: {}, 年级: {}, 学科: {}", 
                teacherId, stage, grade, subject);
        
        List<TeachingPlan> plans = teachingPlanDao.findByTeacherId(teacherId);
        return filterPlans(plans, stage, grade, subject).size();
    }

    @Override
    public long countWithFilters(String stage, String grade, String subject) {
        log.info("统计所有教学计划数量 - 筛选条件: 阶段: {}, 年级: {}, 学科: {}", 
                stage, grade, subject);
        
        List<TeachingPlan> plans = teachingPlanDao.findAll();
        return filterPlans(plans, stage, grade, subject).size();
    }

    private List<TeachingPlan> filterPlans(List<TeachingPlan> plans, String stage, String grade, String subject) {
        return plans.stream()
                .filter(plan -> {
                    boolean matchStage = stage == null || stage.isEmpty() || 
                            (plan.getStage() != null && plan.getStage().equals(stage));
                    boolean matchGrade = grade == null || grade.isEmpty() || 
                            (plan.getGrade() != null && plan.getGrade().equals(grade));
                    boolean matchSubject = subject == null || subject.isEmpty() || 
                            (plan.getSubject() != null && plan.getSubject().equals(subject));
                    
                    return matchStage && matchGrade && matchSubject;
                })
                .collect(Collectors.toList());
    }

    private List<TeachingPlan> filterAndPaginatePlans(List<TeachingPlan> plans, String stage, String grade, String subject, Pageable pageable) {
        List<TeachingPlan> filteredPlans = filterPlans(plans, stage, grade, subject);
        
        int start = (int) pageable.getOffset();
        int end = Math.min((start + pageable.getPageSize()), filteredPlans.size());
        
        if (start >= filteredPlans.size()) {
            return new ArrayList<>();
        }
        
        return filteredPlans.subList(start, end);
    }
} 